<template>
  <view class="vaccine-list-container">
    <!-- 顶部导航 -->
    <view class="header">
      <view class="nav-content">
        <view class="back-btn" @tap="goBack">
          <text class="back-icon">←</text>
        </view>
        <text class="title">全部疫苗</text>
        <view class="placeholder"></view>
      </view>
    </view>

    <!-- 分类筛选 -->
    <view class="filter-section">
      <scroll-view scroll-x class="filter-scroll" :scroll-left="scrollLeft">
        <view 
          v-for="(item, index) in categories" 
          :key="index"
          class="filter-item"
          :class="{ active: currentCategory === item.id }"
          @tap="selectCategory(item)"
        >
          {{ item.name }}
        </view>
      </scroll-view>
    </view>

    <!-- 疫苗列表 -->
    <scroll-view 
      scroll-y 
      class="vaccine-scroll"
      @scrolltolower="loadMore"
      refresher-enabled
      :refresher-triggered="isRefreshing"
      @refresherrefresh="onRefresh"
    >
      <view class="vaccine-list">
        <view v-if="vaccineList.length === 0" class="empty-tip">
          <text>暂无疫苗数据</text>
        </view>
        
        <view 
          class="vaccine-item" 
          v-for="vaccine in vaccineList" 
          :key="vaccine.id"
        >
          <view class="vaccine-info">
            <view class="vaccine-header">
              <text class="vaccine-name">{{ vaccine.name }}</text>
              <text class="vaccine-tag" v-if="vaccine.tag">{{ vaccine.tag }}</text>
            </view>
            <text class="vaccine-desc">{{ vaccine.description }}</text>
            <text class="vaccine-prevention" v-if="vaccine.preventionDescription">
              {{ vaccine.preventionDescription }}
            </text>
            <view class="vaccine-detail">
              <text class="manufacturer" v-if="vaccine.manufacturer">
                生产厂家：{{ vaccine.manufacturer }}
              </text>
              <text class="storage" v-if="vaccine.storageCondition">
                储存条件：{{ vaccine.storageCondition }}
              </text>
            </view>
            <view class="vaccine-bottom">
              <view class="price-box">
                <text class="price-label">价格：</text>
                <text class="price" v-if="vaccine.price > 0">¥{{ vaccine.price }}</text>
                <text class="price free" v-else>免费</text>
              </view>
              <button class="book-btn" @tap="bookVaccine(vaccine)">预约</button>
            </view>
          </view>
        </view>
      </view>
      
      <!-- 加载状态 -->
      <view class="loading-more" v-if="isLoading">正在加载更多...</view>
      <view class="no-more" v-if="noMore">没有更多了</view>
    </scroll-view>
  </view>
</template>

<script>
import { getVaccineCategories, getVaccinesByCategoryId } from '@/api/vaccination'

export default {
  data() {
    return {
      categories: [
        { id: 0, name: '全部' }
      ],
      currentCategory: 0,
      scrollLeft: 0,
      vaccineList: [],
      page: 1,
      isLoading: false,
      noMore: false,
      isRefreshing: false
    }
  },

  onLoad() {
    this.fetchCategories()
    this.fetchVaccineList()
  },

  methods: {
    // 获取疫苗分类数据
    async fetchCategories() {
      try {
        const response = await getVaccineCategories()
        this.categories = [
          { id: 0, name: '全部' },
          ...response
        ]
      } catch (error) {
        console.error('获取疫苗分类失败：', error)
        uni.showToast({
          title: '获取疫苗分类失败',
          icon: 'none'
        })
      }
    },

    // 获取疫苗列表数据
    async fetchVaccineList(showLoading = true) {
      if (this.isLoading) return
      
      try {
        if (showLoading) {
          this.isLoading = true
          uni.showLoading({
            title: '加载中...'
          })
        }
        
        let categoryId = null
        if (this.currentCategory !== 0) {
          categoryId = this.currentCategory
        }
        
        console.log('当前分类ID:', this.currentCategory)
        console.log('请求参数categoryId:', categoryId)
        
        const response = await getVaccinesByCategoryId(categoryId)
        console.log('API响应:', response)
        
        if (response.code === 200 && response.data) {
          this.vaccineList = response.data.map(item => ({
            id: item.id,
            name: item.name,
            tag: item.isHot === 1 ? '热门' : null,
            description: item.description,
            preventionDescription: item.preventionDescription,
            price: item.price,
            manufacturer: item.manufacturer,
            storageCondition: item.storageCondition
          }))
        } else {
          throw new Error(response.errorMessage || '获取数据失败')
        }
      } catch (error) {
        console.error('获取疫苗列表失败：', error)
        uni.showToast({
          title: '获取疫苗列表失败',
          icon: 'none'
        })
      } finally {
        this.isLoading = false
        uni.hideLoading()
      }
    },

    goBack() {
      uni.navigateBack()
    },

    // 选择分类
    async selectCategory(category) {
      if (this.currentCategory === category.id) return
      
      console.log('选择的分类:', category)
      this.currentCategory = category.id
      this.page = 1
      this.noMore = false
      await this.fetchVaccineList()
      
      // 计算滚动位置
      this.$nextTick(() => {
        const query = uni.createSelectorQuery().in(this)
        query.select('.filter-item.active').boundingClientRect(rect => {
          if (rect) {
            const screenWidth = uni.getSystemInfoSync().windowWidth
            this.scrollLeft = rect.left + rect.width / 2 - screenWidth / 2
          }
        }).exec()
      })
    },

    loadMore() {
      if (!this.noMore) {
        this.page++
        this.fetchVaccineList()
      }
    },

    // 下拉刷新
    async onRefresh() {
      this.isRefreshing = true
      this.page = 1
      this.noMore = false
      await this.fetchVaccineList(false)
      this.isRefreshing = false
    },

    // 预约疫苗
    bookVaccine(vaccine) {
      const userInfo = uni.getStorageSync('userInfo')
      if (!userInfo) {
        uni.showModal({
          title: '提示',
          content: '请先登录',
          success: (res) => {
            if (res.confirm) {
              uni.navigateTo({
                url: '/pages/login/login'
              })
            }
          }
        })
        return
      }
      
      uni.navigateTo({
        url: `/pages/vaccination/booking?id=${vaccine.id}`
      })
    }
  }
}
</script>

<style lang="scss">
.vaccine-list-container {
  min-height: 100vh;
  background-color: #f8f8f8;
  
  .header {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    z-index: 100;
    background-color: #fff;
    
    .nav-content {
      margin-top: 44px;
      display: flex;
      align-items: center;
      padding: 0 30rpx;
      height: 88rpx;
      
      .back-btn {
        width: 24rpx;
        height: 24rpx;
        display: flex;
        align-items: center;
        
        .back-icon {
          font-size: 24rpx;
          color: #333;
        }
      }
      
      .title {
        flex: 1;
        text-align: center;
        font-size: 32rpx;
        color: #333;
        font-weight: bold;
      }
      
      .placeholder {
        width: 24rpx;
      }
    }
  }

  .filter-section {
    position: fixed;
    top: calc(44px + 88rpx);
    left: 0;
    right: 0;
    z-index: 99;
    background-color: #fff;
    border-bottom: 1rpx solid #eee;
    
    .filter-scroll {
      white-space: nowrap;
      padding: 20rpx 30rpx;
      
      .filter-item {
        display: inline-block;
        padding: 12rpx 30rpx;
        margin-right: 20rpx;
        font-size: 28rpx;
        color: #666;
        background-color: #f5f5f5;
        border-radius: 28rpx;
        transition: all 0.3s;
        
        &.active {
          color: #fff;
          background-color: #ff5500;
          font-weight: bold;
        }
        
        &:last-child {
          margin-right: 0;
        }
      }
    }
  }

  .vaccine-scroll {
    margin-top: calc(44px + 88rpx + 100rpx);
    height: calc(100vh - 44px - 88rpx - 100rpx);
    
    .vaccine-list {
      padding: 20rpx;
      
      .vaccine-item {
        background-color: #fff;
        border-radius: 12rpx;
        padding: 30rpx;
        margin-bottom: 20rpx;
        
        .vaccine-header {
          display: flex;
          align-items: center;
          margin-bottom: 16rpx;
          
          .vaccine-name {
            font-size: 32rpx;
            color: #333;
            font-weight: bold;
          }
          
          .vaccine-tag {
            margin-left: 16rpx;
            padding: 4rpx 12rpx;
            font-size: 22rpx;
            color: #ff5500;
            background-color: #fff7f5;
            border-radius: 4rpx;
          }
        }
        
        .vaccine-desc {
          font-size: 26rpx;
          color: #666;
          margin-bottom: 20rpx;
          line-height: 1.5;
        }
        
        .vaccine-detail {
          margin-bottom: 20rpx;
          
          .manufacturer, .storage {
            display: block;
            font-size: 26rpx;
            color: #666;
            margin-bottom: 8rpx;
            
            &:last-child {
              margin-bottom: 0;
            }
          }
        }
        
        .vaccine-bottom {
          display: flex;
          justify-content: space-between;
          align-items: center;
          
          .price-box {
            .price-label {
              font-size: 26rpx;
              color: #666;
            }
            
            .price {
              font-size: 36rpx;
              color: #ff5500;
              font-weight: bold;
              
              &.free {
                color: #52c41a;
              }
            }
          }
          
          .book-btn {
            width: 160rpx;
            height: 64rpx;
            line-height: 64rpx;
            background-color: #ff5500;
            color: #fff;
            font-size: 28rpx;
            border-radius: 32rpx;
            padding: 0;
          }
        }
      }
    }
    
    .loading-more, .no-more {
      text-align: center;
      padding: 30rpx;
      font-size: 26rpx;
      color: #999;
    }
  }
}
</style> 